import Vue from 'vue'
import VueRouter from 'vue-router'
import LoginView from '../views/LoginView.vue'
import ErrorView from '../layouts/Error.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect:'/login'
  },
  {
    path: '/login',
    name: 'login',
    component:LoginView
  },
  {
    path:'/home',
    name:'home',
    component: () => import(/* webpackChunkName: "layout" */ '../layouts/Layout.vue'),
    redirect:'/home/student',
    // children:[
    //   {
    //     path: 'student',
    //     name: 'student',
    //     component: () => import(/* webpackChunkName: "student" */ '../views/StudentView.vue')
    //   },
    //   {
    //     path: 'teacher',
    //     name: 'teacher',
    //     component: () => import(/* webpackChunkName: "teacher" */ '../views/TeacherView.vue')
    //   },
    //   {
    //     path: 'admin',
    //     name: 'admin',
    //     component: () => import(/* webpackChunkName: "admin" */ '../views/AdminView.vue')
    //   }
    // ]
  },
  {
    path:'*',
    component:ErrorView
  }
]



const router = new VueRouter({
  mode: 'history',
  routes
})

router.beforeEach((to, from,next) => {
  console.log(to,from,1111)
  //如果要取login 让它去
  if(to.path=='/login'){
    next();
  }else{
    //进的不是登录页，要查看他有哪些权限，有没有添加过路由
    const routerArr=router.getRoutes();
    if(routerArr.length>4){//添加过权限了
      next();
    }else{// 没有添加过权限
       if(sessionStorage.getItem('power')){//是否登录过
          //已经登录过有权限
          JSON.parse(sessionStorage.getItem('power')).forEach((v)=>{
            router.addRoute('home', { path: v.path, component: () => import(/* webpackChunkName: "layout" */ `@/views/${v.component}`) })
          })
          next({path:to.path,replace:true});
       }else{
          //没有登陆过'
          next({path:'/login',replace:true});
       }
    }
  }
})


export default router
